import React, { useState, useEffect } from 'react';
import { useAuth } from '@/hooks/useAuth';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { CustomTitlebar } from '@/components/CustomTitlebar';
import PasswordGeneratorWindow from '@/components/PasswordGeneratorWindow';

interface PasswordLoginProps {
  onSuccess?: () => void;
}

const PasswordLogin: React.FC<PasswordLoginProps> = ({ onSuccess }) => {
  const { verifyMasterPassword, isLoading, error, clearError } = useAuth();
  const [password, setPassword] = useState('');
  const [showPassword, setShowPassword] = useState(false);
  const [loginAttempts, setLoginAttempts] = useState(0);
  const [isLocked, setIsLocked] = useState(false);
  const [toast, setToast] = useState<{ message: string; type: "success" | "error" | "info" } | null>(null);
  const [showErrorToast, setShowErrorToast] = useState(false);
  const [isPasswordGeneratorOpen, setIsPasswordGeneratorOpen] = useState(false);

  // Clear errors when user starts typing
  useEffect(() => {
    if (error) {
      clearError();
    }
  }, [password, error, clearError]);

  // Show error toast when there's an error
  useEffect(() => {
    if (error) {
      setShowErrorToast(true);
      // Auto hide after 3 seconds
      const timer = setTimeout(() => {
        setShowErrorToast(false);
      }, 3000);
      return () => clearTimeout(timer);
    }
  }, [error]);

  // Handle login attempts and lockout
  useEffect(() => {
    if (loginAttempts >= 5) {
      setIsLocked(true);
      // Auto unlock after 5 minutes
      const timer = setTimeout(() => {
        setIsLocked(false);
        setLoginAttempts(0);
      }, 5 * 60 * 1000);
      return () => clearTimeout(timer);
    }
  }, [loginAttempts]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    
    if (!password.trim()) {
      return;
    }

    if (isLocked) {
      return;
    }

    const success = await verifyMasterPassword(password);
    
    if (success) {
      // Login successful, backend has cached the master password
      setPassword('');
      setLoginAttempts(0);
      setShowErrorToast(false);
      // Call success callback if provided
      if (onSuccess) {
        onSuccess();
      }
    } else {
      // Login failed, increment attempts
      setLoginAttempts(prev => prev + 1);
      setPassword('');
      setShowErrorToast(true);
      // Auto hide error toast after 3 seconds
      setTimeout(() => {
        setShowErrorToast(false);
      }, 3000);
    }
  };

  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === 'Enter') {
      handleSubmit(e);
    }
  };

  return (
    <div className="flex flex-col">
      {/* Only show titlebar if not in modal mode */}
      {!onSuccess && (
        <CustomTitlebar
          onSettingsClick={() => setToast({ message: "Settings clicked", type: "info" })}
          onInfoClick={() => setToast({ message: "密码管理器 v1.0.0", type: "info" })}
          onPasswordGeneratorClick={() => setIsPasswordGeneratorOpen(true)}
        />
      )}
      
      {/* Main Content */}
      <div className={`${onSuccess ? 'p-6' : 'h-screen flex items-center justify-center bg-background p-4'}`}>
        <div className={`w-full ${onSuccess ? '' : 'max-w-md'} space-y-6`}>
        <div className="text-center">
          <h1 className="text-2xl font-bold text-foreground mb-2">
            密码管理器
          </h1>
          <p className="text-muted-foreground">
            请输入您的主密码以继续
          </p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="password">主密码</Label>
            <div className="relative">
              <Input
                id="password"
                type={showPassword ? 'text' : 'password'}
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                onKeyPress={handleKeyPress}
                placeholder="请输入主密码"
                className="pr-20"
                disabled={isLoading || isLocked}
                autoFocus
              />
              <Button
                type="button"
                variant="ghost"
                size="sm"
                className="absolute right-0 top-0 h-full px-3 py-2 hover:bg-transparent"
                onClick={() => setShowPassword(!showPassword)}
                disabled={isLoading || isLocked}
              >
                {showPassword ? '隐藏' : '显示'}
              </Button>
            </div>
          </div>

          {/* Login attempts warning */}
          {loginAttempts > 0 && loginAttempts < 5 && (
            <div className="p-3 bg-yellow-50 border border-yellow-200 rounded-md">
              <p className="text-sm text-yellow-600">
                登录失败 {loginAttempts}/5 次，超过5次将锁定5分钟
              </p>
            </div>
          )}

          {/* Account locked warning */}
          {isLocked && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-sm text-red-600">
                账户已锁定，请等待5分钟后重试
              </p>
            </div>
          )}

          {/* Error message */}
          {error && !isLocked && (
            <div className="p-3 bg-red-50 border border-red-200 rounded-md">
              <p className="text-sm text-red-600">{error}</p>
            </div>
          )}

          <Button
            type="submit"
            className="w-full"
            disabled={isLoading || isLocked || !password.trim()}
          >
            {isLoading ? '验证中...' : isLocked ? '账户已锁定' : '登录'}
          </Button>
        </form>

        <div className="text-center text-sm text-muted-foreground">
          <p>忘记密码？</p>
          <p className="mt-1 text-xs">
            请联系管理员或重新安装应用程序
          </p>
        </div>
        </div>
      </div>
      
      {/* Toast Container */}
      {toast && (
        <div className="fixed bottom-4 right-4 bg-background border border-border rounded-lg p-3 shadow-lg">
          <p className="text-sm">{toast.message}</p>
        </div>
      )}
      
      {/* Error Toast - Right top, below titlebar */}
      {showErrorToast && (
        <div className="fixed top-16 right-4 bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800 rounded-lg p-4 shadow-lg z-50 max-w-sm">
          <div className="flex items-start">
            <div className="flex-shrink-0">
              <svg className="w-5 h-5 text-red-400" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
              </svg>
            </div>
            <div className="ml-3">
              <h3 className="text-sm font-medium text-red-800 dark:text-red-200">
                登录失败
              </h3>
              <div className="mt-1 text-sm text-red-700 dark:text-red-300">
                <p>密码错误，请重试</p>
                {loginAttempts > 0 && (
                  <p className="mt-1 text-xs">
                    剩余尝试次数: {5 - loginAttempts}
                  </p>
                )}
              </div>
            </div>
            <div className="ml-auto pl-3">
              <button
                onClick={() => setShowErrorToast(false)}
                className="text-red-400 hover:text-red-600 dark:hover:text-red-300"
              >
                <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                </svg>
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* Password Generator Window */}
      <PasswordGeneratorWindow
        isOpen={isPasswordGeneratorOpen}
        onClose={() => setIsPasswordGeneratorOpen(false)}
      />
    </div>
  );
};

export default PasswordLogin;
